const core = require('mathjs/core');
import Vue from 'vue/dist/vue.esm.js';

const math = core.create();

math.import(require('mathjs/lib/function/arithmetic/add'));
math.import(require('mathjs/lib/function/arithmetic/subtract'));
math.import(require('mathjs/lib/function/arithmetic/multiply'));
math.import(require('mathjs/lib/function/arithmetic/divide'));
math.import(require('mathjs/lib/function/arithmetic/floor'));
math.import(require('mathjs/lib/function/probability/combinations'));

_.mixin({
  combinations: math.combinations,

  unique(arr) {
    const unique = [];
    const repeat = [];
    const hash = {};

    if (!_.isEmpty(arr)) {
      const length = arr.length;
      let i = 0, elem;
      for (; i < length; i++) {
        elem = arr[i];
        if (!hash[elem]) {
          unique.push(elem);
          hash[elem] = true;
        } else {
          repeat.push(elem);
        }
      }
    }

    return {
      unique,
      repeat,
    };
  },

  zhLength(str) {
    return str.replace(/[\u4e00-\u9fa5]/g, '**').length;
  },

  fixedConvert2yuan(money, options) {
    options = _.extend({}, {
      fixed: 2,
      clear: false,
    }, options);
    return _.convert2yuan(money, options);
  },

  convert2yuan(money, options) {
    options = _.extend({}, {
      fixed: 2,
      ratio: 1,
      clear: true,
    }, options);

    return _.formatDiv(money, options.ratio, options);
  },

  formatDiv(money, ratio, options) {
    let format;

    money = money || 0;

    options = _.extend({}, {}, options);

    if (!_.isUndefined(money)) {
      format = _.div(money, ratio);

      if (options.fixed || options.fixed === 0) {
        format = format.toFixed(options.fixed);
      }

      if (options.clear) {
        format = math.add(format, 0);
      }
    }

    return format;
  },

  fixed(number, ratio, symbol = false) {
    number = number.toFixed(ratio);
    if (symbol) {
      if (number > 0) {
        number = `+${number}`;
      } else if (number < 0) {
        number = `-${number}`;
      } else {
        number = `${number}`;
      }
    }

    return number;
  },

  formatMul(money, ratio, {clear = true, fixed = 0} = {clear: true, fixed: 4}) {
    let format;

    if (!_.isUndefined(money)) {
      format = _(money).mul(ratio);

      if (fixed) {
        format = format.toFixed(fixed);
      }

      if (clear) {
        format = math.add(format, 0);
      }
    }

    return format;
  },

  // 格式化时间
  toTime(timestamp, format) {
    return timestamp ? moment(timestamp).format(format || 'YYYY-MM-DD H:mm:ss') : timestamp;
  },

  toDate(timestamp, format) {
    return timestamp ? moment(timestamp).format(format || 'YYYY-MM-DD') : timestamp;
  },

  toPeriod({
             // start: [0, 'week'],
             // end: [0, 'week'],
             start = [],
             end = [],
             format = 'YYYY-MM-DD H:mm:ss',
           }) {
    return {
      startTime: moment().add(start[0], start[1]).startOf(start[1]).format(format),
      endTime: moment().add(end[0], end[1]).endOf(end[1]).format(format),
    };
  },

  toTimestamp({
                // start: [0, 'week'],
                // end: [0, 'week'],
                start = [],
                end = [],
    startEnd = true,
              }) {
    if (startEnd) {
      if (start[1] === 'week') {
        return [moment().add(start[0], start[1]).startOf('isoWeek').valueOf(), moment().add(end[0], end[1]).endOf('isoWeek').valueOf()];
      } else {
        return [moment().add(start[0], start[1]).startOf(start[1]).valueOf(), moment().add(end[0], end[1]).endOf(end[1]).valueOf()];
      }
    } else {
      return [moment().add(start[0], start[1]).valueOf(), moment().add(end[0], end[1]).valueOf()];
    }
  },

  toTodayTimestamp(value, format = 'YYYY/MM/DD') {
    return [moment(value, format).startOf('day').valueOf(), moment(value, format).endOf('day').valueOf()];
  },

  add(arg1, arg2) {
    return math.add(arg1, arg2);
  },

  // 除法   arg1除arg2
  div(arg1, arg2) {
    arg1 = arg1 || 0;
    return math.divide(arg1, arg2);
  },

  // 乘法  arg1乘arg2
  mul(arg1, arg2) {
    arg1 = arg1 || 0;
    return math.multiply(arg1, arg2);
  },

  // 减法 arg1减arg2
  sub(arg1, arg2) {
    return math.subtract(arg1, arg2);
  },

  floor(arg1, index) {
    const sArg1 = String(arg1);
    const pos = sArg1.indexOf('.');
    if (pos > -1) {
      return Number(sArg1.substring(0, pos + index + 1));
    }
    return arg1;
  },

  toDomain(preDomain, fullDomain = 'https://www.ballbet1.com') {
    return `https://${preDomain}.${fullDomain.replace(/^(?:http(?:s)?:\/\/)(?:www.)?(.*)/g, '$1')}`;
  },
  getFirstLevelDomain({fullDomain = document.location.hostname, change = true} = {}) {
    if (fullDomain.indexOf('localhost') > -1 && change) {
      fullDomain = 'www.ballbet1.com';
    }
    return _.takeRight(fullDomain.split('.'), 2).join('.');
  },

  fromNow(timestamp) {
    const now = moment().valueOf();
    let duration = (now - timestamp) / 1000;
    if (duration) {
      if (duration < 60) {
        return `${_.formatDiv(duration, 1, {fixed: 0})}秒前`;
      } else if (duration >= 60 && duration < 3600) {
        return `${_.formatDiv(duration, 60, {fixed: 0})}分钟前`;
      } else if (duration >= 3600 && duration < 86400) {
        return `${_.formatDiv(duration, 3600, {fixed: 0})}小时前`;
      } else if (duration >= 86400 && duration < 604800) {
        return `${_.formatDiv(duration, 86400, {fixed: 0})}天前`;
      } else {
        return _.toDate(timestamp, 'MM-DD');
      }

    } else {
      return '刚刚';
    }
  },

  proxyDownloadUrl() {
    return `${document.domain}/download/download`;
  },

  /**
   * 键盘验证
   */
  validateNumber(keyCode) {
    // 数字
    if (keyCode >= 48 && keyCode <= 57) return true;
    // 小数字键盘
    if (keyCode >= 96 && keyCode <= 105) return true;
    // Backspace, del, 左右方向键
    return keyCode === 8 || keyCode === 46 || keyCode === 37 || keyCode === 39;
  },

  toNegate(value) {
    return -value;
  },

  /**
   *
   * https://github.com/freearhey/vue2-filters.git
   * 12345 => $12,345.00
   *
   * @param {String} symbol
   * @param {Number} decimals Decimal places
   * @param {Object} options
   */

  currency (value, {symbol = '', decimals = 2, options, preDecor = ''} = {}) {
    let thousandsSeparator, symbolOnLeft, spaceBetweenAmountAndSymbol;
    let digitsRE = /(\d{3})(?=\d)/g;
    options = options || {};
    if (value=='' ||  value == '-') return value;
    value = parseFloat(value);
    if (!isFinite(value) || (!value && value !== 0)) return '';

    thousandsSeparator = options.thousandsSeparator != null ? options.thousandsSeparator : ',';

    symbolOnLeft = options.symbolOnLeft != null ? options.symbolOnLeft : true;

    spaceBetweenAmountAndSymbol = options.spaceBetweenAmountAndSymbol != null ? options.spaceBetweenAmountAndSymbol : false;

    let stringified = _.floor(Math.abs(value), decimals).toFixed(decimals);
    if (options.type && options.type === 1) { // type 等于1表示进行四舍五入 2表示无条件进位  默认情况为无条件舍弃
      stringified = _.round(Math.abs(value), decimals).toFixed(decimals);
    } else if (options.type && options.type === 2) {
      stringified = _.ceil(Math.abs(value), decimals).toFixed(decimals);
    }

    stringified = options.decimalSeparator
      ? stringified.replace('.', options.decimalSeparator)
      : stringified;

    let _int = decimals
      ? stringified.slice(0, -1 - decimals)
      : stringified;

    let i = _int.length % 3;

    let head = i > 0
      ? (_int.slice(0, i) + (_int.length > 3 ? thousandsSeparator : ''))
      : '';

    let _float = decimals
      ? stringified.slice(-1 - decimals)
      : '';

    symbol = spaceBetweenAmountAndSymbol
      ? (symbolOnLeft ? symbol + ' ' : ' ' + symbol)
      : symbol;

    symbol = symbolOnLeft
      ? symbol + head +
      _int.slice(i).replace(digitsRE, '$1' + thousandsSeparator) + _float
      : head +
      _int.slice(i).replace(digitsRE, '$1' + thousandsSeparator) + _float + symbol;
    let sign = value < 0 ? '-' : value > 0 ? preDecor : '';
    return sign + symbol;
  },

  toConverter(value, constName) {
    if (_.isArray(value)) {
      return _.map(value, _.partial(_._toConverter, _, constName));
    } else {
      return _._toConverter(value, constName);
    }
  },

  _toConverter(value, constName) {
    try {
      return _.find(consts[constName], {value}).title;
    } catch (e) {
      return value;
      // throw new Error(`${constName}没有找到对应的值${value}`);
    }
  },

  revertConverter(value, constName) {
    if (_.isArray(value)) {
      return _.map(value, _.partial(_._revertConverter, _, constName));
    } else {
      return _._revertConverter(value, constName);
    }
  },

  _revertConverter(title, constName) {
    return _.find(consts[constName], {title}).value;
  },

  downloadIamge(imgsrc, name) {
    //下载图片地址和图片名
    var image = new Image();
    // 解决跨域 Canvas 污染问题
    image.setAttribute('crossOrigin', 'anonymous');
    image.onload = function () {
      var canvas = document.createElement('canvas');
      canvas.width = image.width;
      canvas.height = image.height;
      var context = canvas.getContext('2d');
      context.drawImage(image, 0, 0, image.width, image.height);
      var _dataURL = canvas.toDataURL('image/png'); //得到图片的base64编码数据

      var blob_ = dataURLtoBlob(_dataURL ); // 用到Blob是因为图片文件过大时，在一部风浏览器上会下载失败，而Blob就不会

      var url= {
        name: name || "out", // 图片名称不需要加.png后缀名
        src: blob_
      };

      if (window.navigator.msSaveOrOpenBlob) {   // if browser is IE
        navigator.msSaveBlob(url.src, url.name );//filename文件名包括扩展名，下载路径为浏览器默认路径
      } else {
        var link = document.createElement("a");
        link.setAttribute("href", window.URL.createObjectURL(url.src));
        link.setAttribute("download", url.name + '.png');
        document.body.appendChild(link);
        link.click();
      }
    };
    image.src = imgsrc;

    function dataURLtoBlob(dataurl) {
      var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    }
  },

  toBeiBoName(value) {
    if (value === '188体育') {
      return '贝博体育';
    } else {
      return value;
    }
  }
});

